package com.cuixichang.minimalism.core.security.web;

import com.cuixichang.minimalism.core.security.core.*;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Stack;

public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        Stack<ResponseChain> stack = new Stack<>();
        stack.push(new DefaultResponseChain());
        stack.push(new AccessDeniedChain());
        boolean check;
        do {
            ResponseChain pop = stack.pop();
            check = pop.matching(e);
            if(check){
                pop.invoke(httpServletResponse, e);
            }
        } while (!stack.isEmpty() && !check);
    }
}
